<template>
	<div class="app-container">
		<el-row>
			<el-input style="width: 200px;" v-model="page.mobile" class="filter-item" placeholder="手机号" @keyup.enter.native="serch">
			</el-input>
			<el-input style="width: 200px;" v-model="page.name" class="filter-item" placeholder="姓名" @keyup.enter.native="serch">
			</el-input>
			<el-button class="filter-item" type="primary" icon="search" @click="serch">搜索</el-button>
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="edit" @click="addKeeper">添加</el-button>
		</el-row>
		<el-row>
			<el-table :data="adminList" style="width: 100%">
				<el-table-column prop="id" label="ID" align="center"></el-table-column>
				<el-table-column prop="name" label="姓名" align="left"></el-table-column>
				<el-table-column prop="companyName" label="公司名称" align="left"></el-table-column>
				<el-table-column prop="account" label="账号" align="center"></el-table-column>
				<el-table-column prop="mobile" label="手机号" align="center"></el-table-column>
				<el-table-column prop="email" label="邮箱" align="center"></el-table-column>
				<el-table-column prop="status" label="状态" align="center">
					<template slot-scope="scope">
					<el-switch
					    v-model="scope.row.status"
					    active-color="#409EFF" 
					    inactive-color="#dcdfe6"
					    @change="changeStatus(scope.row)">
					  </el-switch>
					  </template>
				</el-table-column>
				<el-table-column prop="description" label="备注说明" align="center"></el-table-column>
				<el-table-column label="操作" align="center" width=400>
					<template slot-scope="scope">
						<el-button type="primary" icon="edit" @click="editKeeper(scope.row)" size="mini">编辑</el-button>
						<el-button size="mini" type="danger" icon="delete" @click="deleteKeeper(scope.row)">删除</el-button>
						<el-button type="primary" icon="edit" @click="changeRole(scope.row)" size="mini">修改角色</el-button>
						<!--<el-dropdown size="mini" split-button type="primary" @command="handleCommand">
						 	更多
						  <el-dropdown-menu slot="dropdown" >
						    <el-dropdown-item :command="{power:scope.row}">修改权限</el-dropdown-item>
						    
						  </el-dropdown-menu>
						</el-dropdown>-->
					</template>
				</el-table-column>
			</el-table>
		</el-row>
		<el-row>
			<el-pagination layout="total, sizes, prev, pager, next, jumper" 
				:total="totalResultSize" 
				:current-page="page.currentPage"
				:page-count="totalPageSize" 
				:page-sizes="[10, 20, 30, 50]"
      			:page-size="page.pageSize"
      			@size-change="handleSizeChange"
      			@current-change="handleCurrentChange">
			</el-pagination>
		</el-row>
		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			<el-form :model="keeperForm" label-width="110px" :rules="rules" ref="dataForm" :label-position="labelPosition" style='width:70%; margin-left:50px;'>
				<el-row>
					<el-col :span="12">
						<el-form-item label="公司" prop="companyName">
							<el-select v-model="keeperForm.companyId" placeholder="请选择">
								<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
						
					</el-col>
					<el-col :span="12">
						<el-form-item label="账号" prop="account">
							<el-input v-model="keeperForm.account" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="keeperForm.name" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="手机号" prop="mobile">
							<el-input v-model="keeperForm.mobile" auto-complete="off"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="密码" prop="password">
							<el-input v-model="keeperForm.password" auto-complete="off" type="password"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="确认密码" prop="checkPass">
							<el-input v-model="keeperForm.checkPass" auto-complete="off" type="password"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item label="邮箱">
					<el-input v-model="keeperForm.email" auto-complete="off"></el-input>
				</el-form-item>
				
				
				<el-form-item label="说明">
					<el-input v-model="keeperForm.description" type="textarea" :rows="3" auto-complete="off" placeholder="请输入内容"></el-input>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="createData" v-if="dialogStatus === 'create'">确 定</el-button>
				<el-button type="primary" @click="updateData" v-else>确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="权限修改" :visible.sync="showPower">
			<el-form :model="roleData" label-width="110px" size="mini" :label-position="labelPosition" style='width: 400px; margin-left:50px;'>
				<el-form-item label="角色权限">
					<el-checkbox-group 
				    v-model="roleData.roleIdList"
				   	>
				   <el-checkbox v-for="item in roleList" :label="item.id" :key="item.id">{{item.name}}</el-checkbox>
				 </el-checkbox-group>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="showPower = false">取 消</el-button>
				<el-button type="primary" @click="saveUserRole">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { getAdminList, saveAdmin, deleteAdmin, saveUserRole, getRoleList, getRoleByUser} from '@/api/admin'
	import { validateMobile, validateEmail } from '@/utils/validate'
	import { getCompany } from '@/utils/index'
	var validPhone = (rule, value, callback) => {
		if(!value) {
			callback(new Error('请输入电话号码'))
		} else if(!validateMobile(value)) {
			callback(new Error('请输入正确的手机号码'))
		} else {
			callback()
		}
	};
	
	export default {
		name: 'adminList',
		data() {
			var validatePass2 = (rule, value, callback) => {
				if(value === '') {
					callback(new Error('请再次输入密码'));
				} else if(value !== this.keeperForm.password) {
					callback(new Error('两次输入密码不一致!'));
				} else {
					callback();
				}
			};
			return {
				showPower:false,//修改权限弹窗
				adminList: [],
				roleData:{
					id:'',
					roleIdList:[]
				},//选中的角色
				roleList:[],
				dialogFormVisible: false,
				labelPosition:'right',
				dialogStatus: "",
				totalPageSize:0,
				totalResultSize:0,
				page:{
					mobile:"",
					name:"",
					currentPage:1
				},
				textMap: {
					update: '修改管理员',
					create: '添加管理员'
				},
				keeperForm: {
					name: "",
					account: "",
					companyId:"",
					mobile: "",
					password: "",
					checkPass:"",
					description: "",
					email:"",
					status: 1,
					
					
				},
				options: [],
				rules: {
					companyId:[{
						required: true,
						message: '请选择公司',
					}],
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					account: [{
						required: true,
						message: '请输入账号',
						trigger: 'blur'
					}],
					mobile: [{
						required: true,
						validator: validPhone,
						trigger: 'blur'
					}],
					password: [{
						required: true,
						message: '请输入账号密码',
						trigger: 'blur'
					}],
					 checkPass: [{ 
					 	required: true,
					 	validator: validatePass2,
					 	trigger: 'blur' 
					 }],

				}
			}

		},
		created() {
			this.getAdminList({"currentPage":1});
			this.getCompany();
			this.getRoleList();
			
		},
		methods: {
			saveUserRole(){
				
				saveUserRole(this.roleData.id,this.roleData.roleIdList).then((res)=>{
					this.$message({
			          message: '分配角色成功',
			          type: 'success'
			        });
			       this.showPower = false;
			       this.getAdminList(this.page);
				})
			},
			getCompany(){
				getCompany().then((res)=>{
					res.entity.forEach((item)=>{
						this.options.push({value: item.id,label: item.name})
					});
				})
			},
			getRoleList(){
				getRoleList().then((res)=>{
					this.roleList = res.entity.data;
				})
			},
			getRoleByUser(id){//查看管理员权限
				getRoleByUser(id).then((res)=>{
					this.roleData['roleIdList'] = res.entity;
				})
			},
			changeRole(row){//修改角色
				this.roleData['roleIdList'] = [];
				this.roleData['id'] = row.id;
				this.getRoleByUser(row.id);
				this.showPower = true;
			},
			getAdminList(page) {
				let that = this;
				getAdminList(page).then((res) => {
					that.adminList = res.entity.data;
					that.totalPageSize = res.entity.page.totalPageSize;
					that.totalResultSize = res.entity.page.totalResultSize;
					that.page["pageSize"] = res.entity.page.pageSize;
					
				})
			},
			resetTemp() { //清除表单数据
				this.keeperForm = {
					name: "",
					account: "",
					companyId:"",
					mobile: "",
					email: "",
					password: "",
					description: "",
					status: 1
				};
				delete this.keeperForm["id"];
			},
			changeStatus(row){
				let data = {
					id: row.id
				};
				let that = this;
				if(row.status){
					data["status"]=1;
				}else{
					data["status"]=0;
				};
				saveAdmin(data).then((res) => {
					that.getAdminList(that.page);
					that.$notify({
						title: '成功',
						message: '更新状态成功',
						type: 'success',
						duration: 2000
					});
				});
			},
			addKeeper() {
				this.dialogFormVisible = true;
				this.dialogStatus = "create";
				this.resetTemp();
			},
			editKeeper(row){
				let {name,companyId,account,mobile,email,password,description,id} = row;
				this.keeperForm = {
					name,companyId,account,mobile,email,password,description,id
				};
				if(row.status){
					this.keeperForm.status =1;
				}else{
					this.keeperForm.status =0;
				};
				this.dialogFormVisible = true;
				this.dialogStatus = "update";
			},
			/*
			 * 修改或新增
			 * text 修改||添加
			 */
			addAndchang(text){
				let that = this;
				let FormData = this.keeperForm;
				this.$refs['dataForm'].validate((valid) => {
					if(valid) {
						delete FormData["checkPass"];
						saveAdmin(FormData).then((res) => {
							that.getAdminList(that.page);
							that.dialogFormVisible = false
							that.$notify({
								title: '成功',
								message: text+'成功',
								type: 'success',
								duration: 2000
							});
							that.resetTemp();
						})
					}

				});
			},
			createData() {
				this.addAndchang("创建");
			},
			updateData() {
				this.addAndchang("修改");
			},
			deleteKeeper(row){
				let that = this;
				this.$confirm('是否确定删除管理员？ 删除之后将无法恢复！','提示', {
		          confirmButtonText: '确定删除',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		         	deleteAdmin(row.id).then((res)=>{
		         		
		         		that.getAdminList(that.page);
		         		that.$notify({
							title: '成功',
							message: '删除成功',
							type: 'success',
							duration: 2000
						});
						
		         	})
		        });
			},
		     handleCurrentChange(val) {//监听分页值变化
		      	this.page["currentPage"] = val; 
		      	this.getAdminList(this.page);	
		      	
		      	
		     },
		      handleSizeChange(val) {//每页显示多少条数据
			 	this.page["pageSize"] = val;
			 	this.page["currentPage"] = 1;
			 	this.getAdminList(this.page);
			 	
		      },
		      serch(){
		      	this.page["currentPage"] = 1;
		      	this.getAdminList(this.page);
		      }
		}

	}
</script>

<style>
</style>